package com.android.vgongyi.view;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ScrollView;

/**
 * view for waterFall
 * 
 * @author caiying Apr 19, 2012 8:52:02 PM
 */
public class WaterFallView extends ScrollView {
	private static final String TAG = "WaterFallView";
	private OnScrollListener onScrollListener;
	private Handler handler;
	private View view;
	
	public WaterFallView(Context context) {
		super(context);
	}

	public WaterFallView(Context context, AttributeSet attrs) {
		super(context, attrs);

	}

	public WaterFallView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);

	}
	
	public void getView() {
		this.view = getChildAt(0);
		if (view != null) {
			init();
		}
	}
	
	private void init() {
		setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {

				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					break;
				case MotionEvent.ACTION_UP:
					if (view != null && onScrollListener != null) {
						handler.sendMessageDelayed(handler.obtainMessage(1), 200);
					}
					break;

				default:
					break;
				}
				return false;
			}

		});
		
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				Log.i(TAG, "getScrollY--->"+getScrollY());
				switch (msg.what) {
					case 1:
						if (view.getMeasuredHeight() - 20 <= getScrollY()+ getHeight()) {
							if (onScrollListener != null) {
								onScrollListener.onBottom();
								Log.i(TAG, "onBottom");
							}
	
						} else if (getScrollY() == 0) {
							if (onScrollListener != null) {
								onScrollListener.onTop();
								Log.i(TAG, "onTop");
							}
						} else {
							if (onScrollListener != null) {
								onScrollListener.onScroll();
								Log.i(TAG, "onScroll");
							}
						}
						break;
					default:
						break;
				}
			}
		};

	}

	public int computeVerticalScrollRange() {
		return super.computeHorizontalScrollRange();
	}

	public int computeVerticalScrollOffset() {
		return super.computeVerticalScrollOffset();
	}

	@Override
	protected void onScrollChanged(int l, int t, int oldl, int oldt) {
		super.onScrollChanged(l, t, oldl, oldt);
		onScrollListener.onAutoScroll(l, t, oldl, oldt);
		Log.i(TAG, "onAutoScroll");
	}
	
	public interface OnScrollListener {
		void onBottom();

		void onTop();

		void onScroll();

		void onAutoScroll(int l, int t, int oldl, int oldt);
	}

	public void setOnScrollListener(OnScrollListener onScrollListener) {
		this.onScrollListener = onScrollListener;
	}
	
	
}
